<template>
  <div id="competitionDetails">
    <a-row :gutter="[24, 24]">
      <a-col :md="16" :xs="24">
        <a-space direction="vertical" fill size="medium">
          <div style="background-color: white;padding: 20px;">
            <a-descriptions title="比赛公告" >
              <span>{{ competition?.description }}</span>
            </a-descriptions>
            <hr>
            <a-descriptions title="题目信息" v-if="competition?.status != 1" >
              <a-table :ref="tableRef" :columns="columns" :data="questionList" :pagination="false">
                <template #title = "{record}">
                  <a-link v-on:click="toQuestionPage(record.id)" :hoverable="true">
                    {{ record.title }}
                  </a-link>
                </template>
                <template #tagsText="{ record }">
                  <a-space wrap>
                    <a-tag v-for="(tag, index) of record.tagsText" :key="index" color="green">{{ tag }}</a-tag>
                  </a-space>
                </template>
                <template #difficultyText = "{record}">
                  <a-tag style="font-weight: bolder" :style="{color: getColor(record.difficulty)}" size="large">{{ record.difficultyText }}</a-tag>
                </template>
                <template #option = "{record}">
                  
                </template>
              </a-table>
            </a-descriptions>
            
          </div>

        </a-space>
      </a-col>
      <a-col :md="8" :xs="24">
        <div style="display: flex;">
          <div style="background-color: white;padding: 20px;">
          <a-descriptions title="" :column="1" size="medium">
            <span>比赛名称: </span>
            <span>举办者  : </span>
            <span>开始时间: </span>
            <span>结束时间: </span>
            <span>题目数量: </span>
          </a-descriptions>
          </div>
          <div style="background-color: white;padding: 20px;">
          <a-descriptions title="" :column="1" >
            <span>{{ competition?.name }}</span>
            <span>{{ competition?.user?.nickname }}</span>
            <span>{{ competition?.startTime }}</span>
            <span>{{ competition?.endTime }}</span>
            <span>{{ competition?.questionNum }}</span>
          </a-descriptions>
          </div>
        </div>
        
        <div v-if="competition?.status==1" style="background-color: white;padding: 20px;margin-top: 20px; width: 300px;">
          <a-space direction="vertical">
            <a-countdown
            title="距离比赛开始还有"
            :value="startDateTime"
            format=" D 天 H 时 m 分 s 秒"
            style="font-size: 10px;"
            />
            <a-button v-show="isAdd==1" type="primary" v-on:click="toSignup()">点击报名</a-button>
            <a-button v-show="isAdd==0" type="primary" v-on:click="toSignup()">取消报名</a-button>
          </a-space>
        </div>

        <div v-if="competition?.status==2 && isAdd == 0" style="background-color: white;padding: 20px;margin-top: 20px; width: 300px;">
          <a-space direction="vertical">
            <a-countdown
            title="距离比赛结束还有"
            :value="endDateTime"
            format=" H 时 m 分 s 秒"
            style="font-size: 10px;"
            />
          </a-space>
        </div>

      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, watchEffect } from "vue";
import {
  CompetitionControllerService,
  CompetitionVO,
  QuestionVO,
} from "../../../generated";
import { useStore } from "vuex";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";

interface Props {
  id: number;
}
const props = withDefaults(defineProps<Props>(), {
  id: undefined
})

const competition = ref<CompetitionVO>();
const questionList = ref([]);
const tableRef = ref();
const isHover = ref(false);
const isAdd = ref(); // 比赛是否报名 1是没报名

const columns = [
  {
    title: "题目名称",
    slotName: "title",
    width: 240,
  },
  {
    title: "标签",
    slotName: "tagsText",
    width: 240,
  },
  {
    title: "难度",
    slotName: "difficultyText",
    width: 120,
  },
  {
    title: "",
    slotName: "option",
    width: 60,
  },
];

var startDateTime = ref()
var endDateTime = ref()

const router = useRouter();
const store = useStore();

const loadData = async () => {
  const res = await CompetitionControllerService.getCompetitionByIdUsingGet(
    props.id
  )

  const res2 = await CompetitionControllerService.getQuestionListUsingGet(
    props.id
  )

  const userId = store.state.user.loginUser?.id
  const competitionId = res.data?.id
  const res3 = await CompetitionControllerService.getIsRegistryUsingGet(competitionId,userId)
  if(res.code == 0){
    competition.value = res.data
    questionList.value = res2.data
    startDateTime.value = new Date(competition.value?.startDateTime).getTime()
    endDateTime.value = new Date(competition.value?.endDateTime).getTime()
    if(!res.data || res3.data == 0){
      isAdd.value = 1
    } else {
      isAdd.value = 0
    }
  } else {
    message.error("加载失败，" + res.message);  
  }
};

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
  const intervalId = setInterval(() => {
    const currentTime = new Date();
    if (currentTime.getTime() >= endDateTime.value && competition.value?.status == 2) {
      // 比赛结束
      clearInterval(intervalId); // 清除定时器
      CompetitionControllerService.updateCompetitionStateUsingPost(props.id,3)
      location.reload()
    } else if(currentTime.getTime() >= startDateTime.value && competition.value?.status == 1) {
      // 比赛开始
      CompetitionControllerService.updateCompetitionStateUsingPost(props.id,2)
      location.reload()
    }
  }, 1000); // 每秒检查一次
});

//跳转到用户页面
const toUserPage= ()=>{
  router.push({
    path: `/about`
  });
}

const handleMouseOver = ()=>{
  isHover.value = true
}

const handleMouseOut = ()=>{
  isHover.value = false
}

const getColor = (status:number) => {
  switch(status){
    case 1:
      return "green";
    case 2:
      return "blue";
    case 3:
      return "red";
  }

}

const toSignup = async () =>{
  const userId = store.state.user.loginUser?.id
  if(!userId){
    message.error("用户未登录，请先登录")
  } else {
    const competitionId = competition.value?.id
    const res = await CompetitionControllerService.updateUserRegistryUsingGet(competitionId,isAdd.value,userId);
    
    if(res.data == 1){
      if(isAdd.value == 1){
        message.success("报名成功，记得准时参赛");
      } else {
        message.success("取消报名");
      }
      isAdd.value = 1 - isAdd.value
    } else {
      message.error("报名失败")
    }
  }
  
}

const toQuestionPage = (questionId: number) => {
  router.push({
    path: `/view/question/${questionId}`,
  });
};

</script>

<style scoped>
#competitionDetails {
  max-width: 1280px;
  margin: 0 auto;
}

.hover {
  text-decoration-line: underline;
  color: rgb(48, 48, 196);
  cursor: pointer;
}


</style>
